package com.exercise.rpc.test.clent;

import com.exercise.rpc.client.ClientHandler;
import com.exercise.rpc.common.decoder.RpcDecoder;
import com.exercise.rpc.common.encoder.RpcEncoder;
import com.exercise.rpc.common.model.RpcRequest;
import com.exercise.rpc.common.model.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SimpleChatClient implements Runnable {

    private final int port;
    private final String host;

    public SimpleChatClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();

        try{
            //是一个启动NIO服务的辅助启动类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
                            pipeline.addLast(new RpcDecoder(RpcResponse.class));
                            pipeline.addLast(new RpcEncoder(RpcRequest.class));
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            Channel channel = bootstrap.connect(host, port).sync().channel();
            ClientHandler handler = channel.pipeline().get(ClientHandler.class);

            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                RpcRequest rpcRequest = new RpcRequest(in.readLine());
                handler.sendMsg(rpcRequest);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally{
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new SimpleChatClient("127.0.0.1",8080).run();
    }
}